package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduMapUtils;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.异常情况的处理（收货地址为空、超出配送范围、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());//通过id查询地址
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);//收货地址为空
        }

        String address = addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();//收货地址
        String origin = BaiduMapUtils.getCoordinate("合肥市瑶海区闽商国贸1楼");
        String destination = BaiduMapUtils.getCoordinate(address);
        Double distance = BaiduMapUtils.getDistance(origin,destination);
        if(distance > 5000){
            throw new AddressBookBusinessException(MessageConstant.DISTANCE_TOO_FAR);//超出配送范围
        }

        Long userId = BaseContext.getCurrentId();//当前登录用户id
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);//查询当前用户的购物车数据
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);//购物车为空
        }

        //2.构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());//联系人
        order.setNumber(String.valueOf(System.currentTimeMillis()));//订单号
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);//订单状态：待支付
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.insert(order);//返回主键值（useGeneratedKeys）

        //3.订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //4.清理购物车中的数据
        shoppingCartMapper.deleteByUserId(userId);

        //5.封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        ///////////////////////////////////////////////////
    }

    //历史订单查询
    @Override
    public PageResult queryHistory(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.queryHistory(ordersPageQueryDTO);
        for (OrderVO detail : page) {
            detail.setOrderDetailList(orderDetailMapper.selectByOrderId(detail.getId()));
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    //查询订单详情
    @Override
    public OrderVO queryHistoryById(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.queryHistoryById(id);
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailMapper.selectByOrderId(orderVO.getId()));
        return orderVO;
    }

    //取消订单
    @Override
    public void cancellation(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(6)
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    //查询菜品详情
    @Override
    public List<OrderDetail> queryDetailById(Long id) {
        return orderDetailMapper.selectByOrderId(id);
    }


    /**
     * 客户端
     */
    //订单搜索
    @Override
    public PageResult searchOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.queryHistory(ordersPageQueryDTO);
        for (OrderVO orderDish : page) {//遍历订单
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderDish.getId());//一条订单多条菜品
            for (OrderDetail detail : orderDetails) {
                if (orderDish.getOrderDishes() == null) orderDish.setOrderDishes(detail.getName());
                else orderDish.setOrderDishes(orderDish.getOrderDishes() + "," + detail.getName());
            }
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    //各个状态的订单数量统计
    @Override
    public OrderStatisticsVO queryNumber() {
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO
                .builder()
                .confirmed(orderMapper.queryNumber(3))
                .deliveryInProgress(orderMapper.queryNumber(4))
                .toBeConfirmed(orderMapper.queryNumber(2))
                .build();
        return orderStatisticsVO;
    }

    //接单
    @Override
    public void receive(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(3)
                .build();
        orderMapper.update(orders);
    }

    //拒单
    @Override
    public void refuse(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .status(6)
                .build();
        orderMapper.update(orders);
    }

    //取消订单
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .status(6)
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    //派送订单
    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(4)
                .build();
        orderMapper.update(orders);
    }

    //完成订单
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(5)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    //催单
    @Override
    public void reminder(Long id) {
        //查询订单是否存在
        Orders orders = orderMapper.queryHistoryById(id);
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type",2);//2表示催单
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}